const https = require('https');

const SQLHelper = require('./SQLHelper')
///雪花算法生成id
const snowflake = require('./snowflake')
const { formatTime } = require('./util');
const { DATE } = require('mysql/lib/protocol/constants/types');
const { status } = require('express/lib/response');
const { hostname } = require('os');
const multer = require('multer')
const storage = multer.diskStorage({
    destination: './uploads',//保存的路径
    filename: function (req, file, cd) {
        ///获取图片类型
        let fileType = file.originalname.split('.')
        fileType = fileType[fileType.length - 1]
        cd(null, snowflake() + '.' + fileType)
    }
})
const upload = multer({ storage: storage })
module.exports = function (app) {
    ///登录拦截中间件
    function loginRouter(req, res, next) {
        if (req.method.toUpperCase() == "OPTIONS") {
            next()
            return;
        }
        let token = req.headers.token
        if (token) {
            SQLHelper(`select * from session where id = ${token} and state =1`).then(ret => {
                if (ret.length) {
                    let session = ret[0]
                    ///2h
                    if (new Date().getTime() - session.createTime < 2 * 60 * 60 * 1000) {
                        req.session = {
                            userId: session.userId,
                            userName: session.userName
                        }
                        next()
                    } else {
                        res.status(400).send({ errorMsg: '登录超时' })
                    }

                } else {
                    res.status(400).send({ errorMsg: '当前用户未登录' })
                }
            })
        } else {
            res.status(400).send({ errorMsg: '缺少token，请先进行登录' })
        }
    }
    ///让初登陆以为的所有小程序接口都先验证登陆
    app.use('/admin', loginRouter)

    //文件上传
    app.post('/upload', upload.single('file'), (req, res) => {
        res.send(req.file)
    })

    ///微信登录
    app.post('/login', (req, res, next) => {
        let userName = req.body.userName
        let passWord = req.body.passWord
        if (userName && passWord) {
            SQLHelper(`
                select * from user where userName = '${userName}'
            `).then(users => {
                if (users.length) {
                    //正常登录i
                    let user = users[0]
                    if (passWord == user.passWord) {
                        let token = snowflake()
                        ///缓存token到session表
                        SQLHelper(`
                        INSERT INTO session(id,userId,userName,inTime,createTime,platform) 
                        VALUES(${token},'${user._id}','${user.nickName}','${formatTime(new Date())}','${new Date().getTime()}','admin')
                        `).then(ret => {
                            res.send({
                                nickName: user.nickName,
                                token,
                                avatarUrl: user.photo,
                                _id: user._id
                            })
                        })
                    } else {
                        res.send({ errorMsg: "密码错误" })
                    }
                } else {
                    res.send({ errorMsg: "当前用户不存在，请先注册" })
                }
            })

        } else {
            res.send({ errorMsg: "用户名和密码不能为空" })
        }

    })
    //退出登录
    app.get("/admin/logout", (req, res) => {
        SQLHelper(`
            update session set outTime = '${formatTime(new Date())}' , state = 0 where id = '${req.headers.token}'
        `).then(ret => {
            res.send({ msg: "退出登录成功" })
        })
    })
    //修改密码
    app.post('/admin/changePassWord', (req, res) => {
        console.log(req.body)
        let userId = req.session.userId
        let passWord = req.body.passWord
        let newPassWord = req.body.newPassWord
        if (passWord && newPassWord) {
            //通过userid查询用户
            SQLHelper(`select passWord from user where _id = ${userId}`).then(users => {
                let user = users[0]
                //比对密码
                if (user.passWord == passWord) {
                    //比对原密码并修改
                    SQLHelper(`update user set passWord = '${newPassWord}' where _id = '${userId}' `).then(ret => {
                        res.send({ Msg: "修改成功" })
                    })
                } else {
                    res.send({ errorMsg: "原密码错误" })
                }
            })
        } else {
            res.send({ errorMsg: "原密码和新密码不能为空" })
        }
    })
    ///获取首页项目
    ///pageSize每页大小 默认10 
    // pageNum   当前页  默认1
    //type 类型 非必填 bannner 轮播图， category 分类 recommend 为你推荐 
    app.get('/admin/index', (req, res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let title = req.query.title
        let type = req.query.type
        let whereSql = 'from index_region where state = 1'
        //按类型查询
        if (type) whereSql += ` and type = '${type}'`
        //按标题关键字搜索
        if (title) whereSql += ` and title like "%${title}%"`
        SQLHelper(`select count(*) as total  ${whereSql} ;
        select * ${whereSql} limit ${pageSize} offset ${offset}
        `).then(ret => {
            res.send({
                total: ret[0][0].total,
                rows: ret[1]
            })
        })
    })
    ///新增首页项目
    ///img 图片地址 必填
    ///url 链接地址 非必填
    //title 标题 轮播图不填，其他必填
    //status 是否启用 ，非必填，1启用0停用
    //type 类型 非必填 bannner 轮播图， category 分类 recommend 为你推荐
    app.post('/admin/index', (req, res) => {
        let img = req.body.img, url = req.body.url, status = req.body.state
        let type = req.body.type || "banner", title = req.body.title
        if (type != 'banner' && !title) {
            res.send({ errorMsg: "标题不能为空" })
            return
        }
        if (status != 1) status = 0 //默认启动
        ///if(status) status = 1
        if (img) {
            let createTime = new Date().getDate()
            SQLHelper(`
            INSERT INTO index_region(title,img,url,status,state,createTime,unitId,type) 
            VALUES('${title}','${img}','${url}','${status}','1','${createTime}','juzao','${type}')
            `).then(ret => {
                res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: "新增数据失败" })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    ///修改首页项目
    ///indexId主码_id 必填
    app.put('/admin/index', (req, res) => {
        if (req.body.indexId) {
            ///需要修改的项
            let updateTime = new Date().getTime()
            let updateKey = ['img', 'url', 'title', 'status']
            let updateValues = [`updateTime = ${updateTime}`]
            for (let i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些项需要修改
            }
            SQLHelper(`UPDATE index_region set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })



    ///删除地址 逻辑删除
    /// 主indexId码_id 必填
    app.delete('/admin/index', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
            SQLHelper(`
            UPDATE index_region
            set state = 0 
            WHERE _id = ${indexId}
            `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    //获取新闻article列表接口
    //前端传入数据有
    // title:"",
    // type:"article",
    // pageNum:1,
    // pageSize:5
    app.get('/admin/index/article', (req, res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let title = req.query.title
        let type = req.query.type
        let whereSql = 'from article where state = 1'
        //按类型查询
        if (type) whereSql += ` and type = '${type}'`
        //按标题关键字搜索
        if (title) whereSql += ` and title like "%${title}%"`
        SQLHelper(`select count(*) as total  ${whereSql} ;
        select * ${whereSql} limit ${pageSize} offset ${offset}
        `).then(ret => {
            res.send({
                total: ret[0][0].total,
                rows: ret[1]
            })
        })
    })
    //新闻删除接口 单个删除
    app.delete('/admin/index/article', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
            SQLHelper(`
            UPDATE article
            set state = 0 
            WHERE _id = ${indexId}
            `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    ///修改新闻项目
    ///indexId主码_id 必填
    app.put('/admin/index/article', (req, res) => {
        if (req.body.indexId) {
            ///需要修改的项
            let updateTime = new Date().getTime()
            let updateKey = ['img', 'digest', 'title', 'status', 'hot']
            let updateValues = [`updateTime = ${updateTime}`]
            for (let i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些项需要修改
            }
            SQLHelper(`UPDATE article set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    //增加新闻项目 
    //头部必填，标题必填 摘要 热门非必填
    app.post('/admin/index/article', (req, res) => {
        let img = req.body.img, digest = req.body.digest, status = req.body.state
        let title = req.body.title, hot = req.body.hot
        if (!img && !title && !digest) {
            res.send({ errorMsg: "标题，摘要，图片不能为空" })
            return
        }
        if (status != 1) status = 0 //默认不启动
        if (hot != 1) hot = 0//默认不热门
        ///if(status) status = 1
        if (img && title) {
            let createTime = new Date().getDate()
            SQLHelper(`
            INSERT INTO article(title,img,digest,status,state,createTime,unitId,type,hot) 
            VALUES('${title}','${img}','${digest}','${status}','1','${createTime}','juzao','news','${hot}')
            `).then(ret => {
                res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: "新增数据失败" })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    //获取品牌brand列表接口
    //前端传入数据有
    // name:"",
    // pageNum:1,
    // pageSize:5
    app.get('/admin/index/brand', (req, res) => {
        let pageSize = req.query.pageSize || 1000
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let name = req.query.name
        let whereSql = 'from brand where state = 1'
        //按标题关键字搜索
        if (name) whereSql += ` and name like "%${name}%"`
        SQLHelper(`select count(*) as total  ${whereSql} ;
        select * ${whereSql} limit ${pageSize} offset ${offset}
        `).then(ret => {
            res.send({
                total: ret[0][0].total,
                rows: ret[1]
            })
        })
    })
    //增加品牌项目 
    //img必填 品牌名称必填
    app.post('/admin/index/brand', (req, res) => {
        let img = req.body.img
        let name = req.body.name
        if (!img && !name) {
            res.send({ errorMsg: "logo 品牌名不能为空" })
            return
        }
        if (img && name) {
            let createTime = new Date().getDate()
            SQLHelper(`
            INSERT INTO brand(name,img,state,createTime,unitId) 
            VALUES('${name}','${img}','1','${createTime}','juzao')
            `).then(ret => {
                res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: "新增数据失败" })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    ///修改品牌项目
    ///indexId主码_id 必填
    app.put('/admin/index/brand', (req, res) => {
        if (req.body.indexId) {
            ///需要修改的项
            let updateTime = new Date().getTime()
            let updateKey = ['img', 'name']
            let updateValues = [`updateTime = ${updateTime}`]
            for (let i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些项需要修改
            }
            SQLHelper(`UPDATE brand set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    //新闻删除接口 单个删除
    app.delete('/admin/index/brand', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
            SQLHelper(`
            UPDATE brand
            set state = 0 
            WHERE _id = ${indexId}
            `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    ///获取商品项目
    ///pageSize每页大小 默认10 
    // pageNum   当前页  默认1
    app.get('/admin/index/product', (req, res) => {
        let pageSize = req.query.pageSize || 1000
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let name = req.query.name //查询条件
        if (name) {
            SQLHelper(`
            select count(*) as total from (select  b.name as brandName ,p.* from product as p left join brand as b on p.brandId = b._id where  (p.name like '%${name}%' or b.name like '%${name}%') and p.state = 1 )as total;
            select b.name as brandName ,p.* from product as p left join brand as b on p.brandId = b._id
            where (p.name like '%${name}%' or b.name like '%${name}%') and p.state = 1 
            limit ${pageSize} offset ${offset}
            `).then(ret => {
                res.send({
                    total: ret[0][0].total,
                    rows: ret[1]
                })
            })
        } else {
            SQLHelper(`
            select count(*) as total from (select  b.name as brandName ,p.* from product as p left join brand as b on p.brandId = b._id where p.state = 1  )as total;
            select b.name as brandName ,p.* from product as p left join brand as b on p.brandId = b._id
            where p.state = 1
            limit ${pageSize} offset ${offset}
            `).then(ret => {
                res.send({
                    total: ret[0][0].total,
                    rows: ret[1]
                })
            })
        }
    })
    ///修改商品项目
    ///indexId主码_id 必填
    app.put('/admin/index/product', (req, res) => {
        if (req.body.indexId) {
            ///需要修改的项
            let updateTime = new Date().getTime()
            let updateKey = ['imgs', 'name', 'brandId', 'sales', 'status']
            let updateValues = [`updateTime = ${updateTime}`]
            for (let i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些项需要修改
            }
            SQLHelper(`UPDATE product set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    //商品删除接口 单个删除
    app.delete('/admin/index/product', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
            SQLHelper(`
            UPDATE product
            set state = 0 
            WHERE _id = ${indexId}
            `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    //增加商品项目 
    //imgs必填 商品名称 必填status品牌名称必填
    app.post('/admin/index/product', (req, res) => {
        let imgs = req.body.imgs
        let name = req.body.name
        let brandId = req.body.brandId
        let sales = req.body.sales
        let status = req.body.status
        if (!imgs && !name && !brandId) {
            res.send({ errorMsg: "品牌名轮播图名称不能为空" })
            return
        }
        if (imgs && name && brandId) {
            let createTime = new Date().getDate()
            SQLHelper(`
            INSERT INTO product(name,imgs,state,createTime,unitId,brandId,sales,status) 
            VALUES('${name}','${imgs}','1','${createTime}','juzao','${brandId}','${sales}','${status}')
            `).then(ret => {
                res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: "新增数据失败" })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }

    })
    ///获取单品项目
    ///pageSize每页大小 默认10 
    // pageNum   当前页  默认1
    //name 为模糊查询关键字
    app.get('/admin/index/sku', (req, res) => {
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let name = req.query.name
        let whereSql = 'from sku where state = 1'
        //按标题关键字搜索
        if (name) whereSql += ` and (skuId like "%${name}%" or productName like "%${name}%" or props like "%${name}%")`
        SQLHelper(`select count(*) as total  ${whereSql} ;
        select * ${whereSql} limit ${pageSize} offset ${offset}
        `).then(ret => {
            res.send({
                total: ret[0][0].total,
                rows: ret[1]
            })
        })
    })
    //商品删除接口 单个删除
    app.delete('/admin/index/sku', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
            SQLHelper(`
            UPDATE sku
            set state = 0 
            WHERE _id = ${indexId}
            `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    //增加单品项目  _id:0,
    //imgs productname  productin skuID必填
    app.post('/admin/index/sku', (req, res) => {
        let imgs = req.body.imgs, skuId = req.body.skuId, salePrice = req.body.salePrice, originalPrice = req.body.originalPrice
        let props = req.body.props, productName = req.body.productName, productId = req.body.productId
        if (!imgs && !productName && !skuId) {
            res.send({ errorMsg: "图片，商品名称，skuid不能为空" })
            return
        }
        if (imgs && productName && skuId) {
            let createTime = new Date().getDate()
            SQLHelper(`
            INSERT INTO sku(skuId,salePrice,originalPrice,productId,productName,imgs,props,state,unitId) 
            VALUES('${skuId}','${salePrice}','${originalPrice}','${productId}','${productName}','${imgs}','${props}','1','juzao')
            `).then(ret => {
                res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: "新增数据失败" })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    ///修改单品项目
    ///indexId主码_id 必填
    app.put('/admin/index/sku', (req, res) => {
        if (req.body.indexId) {
            ///需要修改的项
            let updateTime = new Date().getTime()
            let updateKey = ['skuId', 'salePrice', 'originalPrice', 'productId', 'productName', 'imgs', 'props']
            let updateValues = [`updateTime = ${updateTime}`]
            for (let i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value !== undefined) updateValues.push(`${key}='${value}'`)///判断哪些项需要修改
            }
            SQLHelper(`UPDATE sku set ${updateValues.join(',')} WHERE _id = ${req.body.indexId}`).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    //检验唯一id
    app.put("/admin/index/checkId", (req, res) => {
        let skuId = req.body.skuId
        SQLHelper(`select *from sku where skuId = '${skuId}'`).then(ret => {
            if (ret == false) {
                res.send(true)
            }
            else {
                res.send(false)
            }
        })
    })
    ///这处理分类数据 这里前台分类列表不需要传值
    app.get('/admin/index/Cat', (req, res) => {
        let date1 = []//用于存放第一级
        let date2 = []//存放第二级
        SQLHelper(`SELECT * FROM cateleve where state = 1;
        SELECT * FROM category where state = 1
        `).then((ret) => {
            date1 = ret[0]
            date2 = ret[1]
            for (let i = 0; i < date1.length; i++) {
                date1[i].children = []
                for (let f = 0; f < date2.length; f++) {
                    if (date2[f].parentId == date1[i].id) {
                        date1[i].children.push(date2[f])
                    }
                }
            }
            res.send(date1)
        })
    })
    //分类删除接口
    app.delete('/admin/index/Cat', (req, res) => {
        let indexId = req.query.indexId
        if (indexId) {
            SQLHelper(`
            UPDATE category
            set state = 0 
            WHERE _id = ${indexId}
            `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数删除失败了' })
        }
    })
    //增加分类项目 
    //name必填 
    app.post('/admin/index/Cat', (req, res) => {
        let name = req.body.name
        let parentId = req.body.parentId
        let id = snowflake()
        if (!name && !parentId) {
            res.send({ errorMsg: "没有传入name和parentId不能为空" })
            return
        }
        if (name && parentId) {
            let createTime = new Date().getDate()
            SQLHelper(`
            INSERT INTO category(name,id,state,createTime,unitId,parentId,level) 
            VALUES('${name}','${id}','1','${createTime}','juzao','${parentId}','2')
            `).then(ret => {
                res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: "新增数据失败" })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })
    //获取分类商品的列表
    app.get('/admin/index/productSku', (req, res) => {
        let categoryId = req.query.categoryId
        let pageSize = req.query.pageSize || 10
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let name = req.query.name
        //关联表进行查询
        if (categoryId) {
            SQLHelper(`select count(*) as total from (SELECT product.* ,category_product.categoryId,brand.name AS brandName FROM product LEFT JOIN category_product ON product._id = category_product.productId LEFT JOIN brand on product.brandId = brand._id
                WHERE categoryId = '${categoryId}' AND product.state = 1 AND product.name LIKE '%${name}%')as total;
        
            SELECT product.* ,category_product.categoryId,brand.name AS brandName FROM product LEFT JOIN category_product ON product._id = category_product.productId LEFT JOIN brand on product.brandId = brand._id
        WHERE categoryId = '${categoryId}' AND product.state = 1 AND product.name LIKE '%${name}%' limit ${pageSize} offset ${offset}
       `).then(ret => {
                res.send({
                    total: ret[0][0].total,
                    rows: ret[1]
                })
            })
        } else {
            res.send({ errorMsg: '没有传入categoryId参数错误' })
        }
    })
    //用于更改商品的分类链接表
    app.post('/admin/index/categoryIdfun', (req, res) => {
        let productId = req.body._id
        let categoryId = req.body.categoryId
        if (categoryId && productId) {
            SQLHelper(`
            INSERT INTO category_product(productId,categoryId) 
            VALUES('${productId}','${categoryId}')
            `).then(ret => {
                res.send(ret.insertId ? { _id: ret.insertId } : { errorMsg: "新增数据失败" })
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }

    })

}
